using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using Microsoft.Win32;
using SvgToFontConverter.Models;
using SvgToFontConverter.Services;
using SvgToFontConverter.ViewModels;
// Windows命名空间引用已移除，直接使用类名
using MessageBox = System.Windows.MessageBox;

namespace SvgToFontConverter
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainViewModel _viewModel;
        private FontForgeService _fontForgeService;
        private FontelloCliService _fontelloCliService;
        private Svg2TtfService _svg2TtfService;
        private EngineConfigService _engineConfigService;
        private EngineConfig _engineConfig;
        private CancellationTokenSource _cancellationTokenSource;
        private bool _isConverting = false;
        private PerformanceSettings _performanceSettings;

        public MainWindow()
        {
            InitializeComponent();
            _viewModel = new MainViewModel();
            _fontForgeService = new FontForgeService();
            _fontelloCliService = new FontelloCliService();
            _svg2TtfService = new Svg2TtfService();
            _engineConfigService = new EngineConfigService();
            _performanceSettings = PerformanceSettings.GetDefault();
            DataContext = _viewModel;
            
            // 初始化界面
            InitializeUI();
        }

        private void InitializeUI()
        {
            // 设置默认输出路径
            txtOutputFolder.Text = Path.Combine(Environment.CurrentDirectory, "output");
            
            // 加载引擎配置
            LoadEngineConfig();
            
            // 更新引擎状态显示
            UpdateEngineStatusDisplay();
            
            // 执行SVG路径提取测试
            try
            {
                TestSvgPathExtraction();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"SVG路径提取测试失败: {ex.Message}");
            }
        }
        
        private void LoadEngineConfig()
        {
            try
            {
                _engineConfig = _engineConfigService.LoadConfig();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载引擎配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                _engineConfig = _engineConfigService.CreateDefaultConfig();
            }
        }

        private void UpdateEngineStatusDisplay()
        {
            try
            {
                string engineName = "未配置";
                string status = "未配置";
                string description = "请点击上方的\"引擎配置\"按钮进行配置";
                Brush statusColor = Brushes.Orange;

                if (_engineConfig.SelectedEngine == EngineType.FontForge)
                {
                    engineName = "FontForge";
                    if (_engineConfig.FontForge.IsValidated)
                    {
                        status = "已配置";
                        description = $"FontForge 路径: {_engineConfig.FontForge.InstallPath}";
                        statusColor = Brushes.Green;
                    }
                    else
                    {
                        status = "未配置";
                        description = "FontForge 路径未配置或无效";
                        statusColor = Brushes.Red;
                    }
                }
                else if (_engineConfig.SelectedEngine == EngineType.FontelloCli)
                {
                    engineName = "Fontello CLI";
                    if (_engineConfig.FontelloCli.IsValidated)
                    {
                        status = "已配置";
                        description = $"Node.js: {_engineConfig.FontelloCli.NodeJsPath}\nFontello CLI: {_engineConfig.FontelloCli.FontelloCliPath}";
                        statusColor = Brushes.Green;
                    }
                    else
                    {
                        status = "未配置";
                        description = "Node.js 或 Fontello CLI 路径未配置或无效";
                        statusColor = Brushes.Red;
                    }
                }
                else if (_engineConfig.SelectedEngine == EngineType.Svg2Ttf)
                {
                    engineName = "SVG2TTF";
                    if (_engineConfig.Svg2Ttf.IsValidated)
                    {
                        status = "已配置";
                        description = $"Node.js: {_engineConfig.Svg2Ttf.NodeJsPath}\nSVG2TTF: 已安装";
                        statusColor = Brushes.Green;
                    }
                    else
                    {
                        status = "未配置";
                        description = "Node.js 路径未配置或 SVG2TTF 未安装";
                        statusColor = Brushes.Red;
                    }
                }

                // 更新UI元素
                lblEngineTitle.Text = $"当前服务：{engineName}";
                lblEngineDescription.Text = description;
                lblEngineStatus.Text = $"状态：{status}";
                lblEngineStatus.Foreground = statusColor;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新引擎状态显示失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        // 旧的FontForge配置方法已被新的引擎系统替代
        
        // 旧的FontForge自动检测方法已被新的引擎系统替代
        
        // 旧的FontForge配置保存方法已被新的引擎系统替代

        // 旧的FontForge状态检查方法已被新的引擎系统替代

        // 旧的FontForge粘贴事件已被新的引擎系统替代

        // 旧的FontForge文本改变和浏览事件已被新的引擎系统替代

        private void BrowseSvg_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择包含SVG文件的文件夹";
                
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtSvgFolder.Text = dialog.SelectedPath;
                    LoadSvgFiles(dialog.SelectedPath);
                }
            }
        }

        private void LoadSvgFiles(string folderPath)
        {
            try
            {
                var svgFiles = Directory.GetFiles(folderPath, "*.svg")
                    .Select(file => new SvgFileInfo
                    {
                        FilePath = file,
                        FileName = Path.GetFileName(file),
                        UnicodeChar = GetUnicodeCharFromFileName(Path.GetFileNameWithoutExtension(file)),
                        Status = "待转换"
                    })
                    .ToList();

                _viewModel.SvgFiles.Clear();
                foreach (var file in svgFiles)
                {
                    _viewModel.SvgFiles.Add(file);
                }

                lstSvgFiles.ItemsSource = _viewModel.SvgFiles;
                lblFileCount.Text = $"文件数量: {svgFiles.Count}";
                UpdateConvertButtonState();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载SVG文件时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private string GetUnicodeCharFromFileName(string fileName)
        {
            try
            {
                if (int.TryParse(fileName, System.Globalization.NumberStyles.HexNumber, null, out int unicode))
                {
                    return $"U+{unicode:X4} ({(char)unicode})";
                }
            }
            catch
            {
                // 忽略转换错误
            }
            return "无效编码";
        }

        private void BrowseOutput_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择输出文件夹";
                dialog.SelectedPath = txtOutputFolder.Text;
                
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtOutputFolder.Text = dialog.SelectedPath;
                }
            }
        }

        private void UpdateConvertButtonState()
        {
            try
            {
                if (btnStartConversion == null || txtOutputFolder == null || 
                    _engineConfig == null || _viewModel == null)
                    return;
                    
                // 检查当前服务是否配置有效
                bool engineValid = false;
                if (_engineConfig.SelectedEngine == EngineType.FontForge)
                {
                    engineValid = _engineConfig.FontForge.IsValidated;
                }
                else if (_engineConfig.SelectedEngine == EngineType.FontelloCli)
                {
                    engineValid = _engineConfig.FontelloCli.IsValidated;
                }
                else if (_engineConfig.SelectedEngine == EngineType.Svg2Ttf)
                {
                    engineValid = _engineConfig.Svg2Ttf.IsValidated;
                }
                    
                btnStartConversion.IsEnabled = !_isConverting && 
                                             engineValid &&
                                             _viewModel.SvgFiles.Count > 0 &&
                                             !string.IsNullOrWhiteSpace(txtOutputFolder.Text);
            }
            catch (Exception ex)
            {
                // 记录错误但不中断程序
                System.Diagnostics.Debug.WriteLine($"UpdateConvertButtonState error: {ex.Message}");
            }
        }

        private async void StartConversion_Click(object sender, RoutedEventArgs e)
        {
            if (_isConverting) return;

            try
            {
                _isConverting = true;
                _cancellationTokenSource = new CancellationTokenSource();
                
                btnStartConversion.IsEnabled = false;
                btnStopConversion.IsEnabled = true;
                
                // 确保输出目录存在
                Directory.CreateDirectory(txtOutputFolder.Text);
                
                var selectedFiles = _viewModel.SvgFiles.Where(f => f.Status != "已完成").ToList();
                progressBar.Maximum = selectedFiles.Count;
                progressBar.Value = 0;
                
                lblProgress.Text = "开始转换...";
                lblStatusBar.Text = "正在转换";
                
                await ConvertSvgFiles(selectedFiles, _cancellationTokenSource.Token);
                
                if (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    lblProgress.Text = "转换完成！";
                    lblStatusBar.Text = "转换完成";
                    MessageBox.Show("SVG转字体转换完成！", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (OperationCanceledException)
            {
                lblProgress.Text = "转换已取消";
                lblStatusBar.Text = "已取消";
            }
            catch (Exception ex)
            {
                lblProgress.Text = "转换失败";
                lblStatusBar.Text = "转换失败";
                MessageBox.Show($"转换过程中出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isConverting = false;
                btnStartConversion.IsEnabled = true;
                btnStopConversion.IsEnabled = false;
                UpdateConvertButtonState();
            }
        }

        private async Task ConvertSvgFiles(List<SvgFileInfo> files, CancellationToken cancellationToken)
        {
            try
            {
                // 分批处理大量文件以提高性能和用户体验
                // 根据文件数量自动调整批处理大小
                var batchSize = _performanceSettings.GetOptimalBatchSize(files.Count);
                var totalFiles = files.Count;
                var processedFiles = 0;
                
                lblProgress.Text = $"准备转换 {totalFiles} 个SVG文件（分批处理以提高性能）...";
                progressBar.Value = 0;
                progressBar.Maximum = totalFiles;
                
                // 刷新UI
                await Dispatcher.InvokeAsync(() => { });
                
                if (cancellationToken.IsCancellationRequested)
                    return;
                
                // 分批处理文件
                var batches = files.Select((file, index) => new { file, index })
                                  .GroupBy(x => x.index / batchSize)
                                  .Select(g => g.Select(x => x.file).ToList())
                                  .ToList();
                
                var allSuccess = true;
                
                for (int batchIndex = 0; batchIndex < batches.Count; batchIndex++)
                {
                    if (cancellationToken.IsCancellationRequested)
                        return;
                    
                    var batch = batches[batchIndex];
                    var batchNumber = batchIndex + 1;
                    
                    // 更新当前批次文件状态
                    foreach (var file in batch)
                    {
                        file.Status = $"批次 {batchNumber} 转换中...";
                    }
                    
                    lblProgress.Text = $"正在处理第 {batchNumber}/{batches.Count} 批次 ({batch.Count} 个文件)...";
                    await Dispatcher.InvokeAsync(() => { });
                    
                    // 获取当前批次的SVG文件路径
                    var svgFilePaths = batch.Select(f => f.FilePath).ToList();
                    
                    // 使用智能缩放（在Python脚本中自动处理）
                    double scaleRatio = 1.0;
                    
                    // 获取字体基本信息
                    var fontName = string.IsNullOrWhiteSpace(txtFontName.Text) ? "CustomFont" : txtFontName.Text;
                    var fontFamily = string.IsNullOrWhiteSpace(txtFontFamily.Text) ? fontName : txtFontFamily.Text;
                    
                    // 创建文件名（如果启用批次命名，则添加批次后缀）
                    var fileName = chkUseBatchNaming.IsChecked == true ? 
                        $"{fontName}_Batch{batchNumber:D3}" : fontName;
                    
                    // 字体内部名称保持不变（不添加批次后缀）
                    var internalFontName = fontName;
                    
                    // 根据当前选择的引擎进行转换
                    bool batchSuccess = false;
                    if (_engineConfig.SelectedEngine == EngineType.FontForge && _engineConfig.FontForge.IsValidated)
                    {
                        batchSuccess = await _fontForgeService.ConvertSvgFilesToFontAsync(
                            _engineConfig.FontForge.InstallPath,
                            svgFilePaths,
                            txtOutputFolder.Text,
                            fileName, // 文件名（可能包含批次后缀）
                            scaleRatio,
                            cancellationToken,
                            _performanceSettings,
                            internalFontName, // 字体内部名称（不包含批次后缀）
                            fontFamily, // 字体族名称
                            txtFontAuthor.Text, // 字体作者
                            txtFontVersion.Text); // 字体版本
                    }
                    else if (_engineConfig.SelectedEngine == EngineType.FontelloCli && _engineConfig.FontelloCli.IsValidated)
                    {
                        batchSuccess = await _fontelloCliService.ConvertSvgToFontAsync(
                            svgFilePaths,
                            txtOutputFolder.Text,
                            fileName, // 文件名（可能包含批次后缀）
                            _engineConfig.FontelloCli,
                            cancellationToken,
                            _performanceSettings,
                            internalFontName, // 字体内部名称（不包含批次后缀）
                            fontFamily, // 字体族名称
                            txtFontAuthor.Text, // 字体作者
                            txtFontVersion.Text); // 字体版本
                    }
                    else if (_engineConfig.SelectedEngine == EngineType.Svg2Ttf && _engineConfig.Svg2Ttf.IsValidated)
                    {
                        // 为SVG2TTF构建完整的TTF文件路径
                        var ttfFilePath = Path.Combine(txtOutputFolder.Text, $"{fileName}.ttf");
                        batchSuccess = await _svg2TtfService.ConvertSvgToTtfAsync(
                            svgFilePaths,
                            ttfFilePath,
                            fileName, // fileName
                            _engineConfig.Svg2Ttf,
                            cancellationToken,
                            internalFontName, // fontName
                            fontFamily, // fontFamily
                            txtFontAuthor.Text, // fontAuthor
                            txtFontVersion.Text); // fontVersion
                    }
                    else
                    {
                        throw new InvalidOperationException("当前选择的引擎未配置或配置无效，请先配置引擎。");
                    }
                    
                    if (cancellationToken.IsCancellationRequested)
                        return;
                    
                    if (batchSuccess)
                    {
                        // 更新当前批次文件状态为已完成
                        foreach (var file in batch)
                        {
                            file.Status = "已完成";
                        }
                        
                        // 如果选择了删除原文件，删除当前批次的文件
                        if (chkDeleteSvgAfterConvert.IsChecked == true)
                        {
                            foreach (var file in batch)
                            {
                                try
                                {
                                    File.Delete(file.FilePath);
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine($"删除文件失败: {file.FilePath}, 错误: {ex.Message}");
                                }
                            }
                        }
                    }
                    else
                    {
                        // 更新当前批次文件状态为转换失败
                        foreach (var file in batch)
                        {
                            file.Status = "转换失败";
                        }
                        allSuccess = false;
                    }
                    
                    // 更新总体进度
                    processedFiles += batch.Count;
                    progressBar.Value = processedFiles;
                    
                    // 显示详细进度信息
                    var completedBatches = batchIndex + 1;
                    var remainingBatches = batches.Count - completedBatches;
                    lblProgress.Text = $"已完成 {completedBatches}/{batches.Count} 批次 ({processedFiles}/{totalFiles} 文件)" +
                                     (remainingBatches > 0 ? $"，剩余 {remainingBatches} 批次" : "");
                    
                    await Dispatcher.InvokeAsync(() => { });
                    
                    // 在批次之间添加短暂延迟，避免系统过载
                    if (batchIndex < batches.Count - 1)
                    {
                        await Task.Delay(_performanceSettings.BatchDelayMs, cancellationToken);
                    }
                }
                
                if (allSuccess)
                {
                    lblProgress.Text = $"转换完成！生成了 {batches.Count} 个字体文件，共包含 {totalFiles} 个字符";
                }
                else
                {
                    lblProgress.Text = $"部分转换失败。已完成 {files.Count(f => f.Status == "已完成")} 个文件";
                }
            }
            catch (Exception ex)
            {
                // 更新所有文件状态为错误
                foreach (var file in files)
                {
                    if (file.Status != "已完成")
                    {
                        file.Status = $"错误: {ex.Message}";
                    }
                }
                
                lblProgress.Text = "转换过程中发生错误";
            }
        }

        private void StopConversion_Click(object sender, RoutedEventArgs e)
        {
            _cancellationTokenSource?.Cancel();
            btnStopConversion.IsEnabled = false;
        }

        private void EngineConfig_Click(object sender, RoutedEventArgs e)
        {
            var configWindow = new EngineConfigWindow();
            if (configWindow.ShowDialog() == true)
            {
                // 重新加载配置
                LoadEngineConfig();
                UpdateEngineStatusDisplay();
                lblStatusBar.Text = "引擎配置已更新";
            }
        }

        private void PerformanceSettings_Click(object sender, RoutedEventArgs e)
        {
            var settingsWindow = new PerformanceSettingsWindow(_performanceSettings);
            if (settingsWindow.ShowDialog() == true)
            {
                _performanceSettings = settingsWindow.Settings;
                // 显示当前性能模式
                string modeName = GetPerformanceModeName(_performanceSettings);
                lblStatusBar.Text = $"就绪 - {modeName}";
            }
        }

        private string GetPerformanceModeName(PerformanceSettings settings)
        {
            if (settings.BatchSize >= 1000 && settings.BatchDelayMs <= 100)
                return "高性能模式";
            else if (settings.BatchSize <= 200 && settings.BatchDelayMs >= 500)
                return "保守模式";
            else
                return "默认模式";
        }

        private void ConvertFileNames_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtSvgFolder.Text) || !Directory.Exists(txtSvgFolder.Text))
            {
                MessageBox.Show("请先选择SVG文件夹", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                var svgFiles = Directory.GetFiles(txtSvgFolder.Text, "*.svg");
                var convertedFiles = new List<string>();
                var failedFiles = new List<string>();

                foreach (var filePath in svgFiles)
                {
                    var fileName = Path.GetFileNameWithoutExtension(filePath);
                    var directory = Path.GetDirectoryName(filePath);

                    // 检查文件名是否已经是Unicode编码
                    if (IsValidUnicodeFileName(fileName))
                    {
                        continue; // 跳过已经是Unicode编码的文件
                    }

                    // 尝试将文件名转换为Unicode编码
                    var unicodeFileName = ConvertTextToUnicodeFileName(fileName);
                    if (!string.IsNullOrEmpty(unicodeFileName))
                    {
                        var newFilePath = Path.Combine(directory, unicodeFileName + ".svg");
                        
                        // 检查新文件名是否已存在
                        if (File.Exists(newFilePath))
                        {
                            failedFiles.Add($"{fileName} -> {unicodeFileName} (文件已存在)");
                            continue;
                        }

                        try
                        {
                            File.Move(filePath, newFilePath);
                            convertedFiles.Add($"{fileName} -> {unicodeFileName}");
                        }
                        catch (Exception ex)
                        {
                            failedFiles.Add($"{fileName} -> {unicodeFileName} (重命名失败: {ex.Message})");
                        }
                    }
                    else
                    {
                        failedFiles.Add($"{fileName} (无法转换为Unicode)");
                    }
                }

                // 显示转换结果
                var result = new StringBuilder();
                if (convertedFiles.Count > 0)
                {
                    result.AppendLine($"成功转换 {convertedFiles.Count} 个文件：");
                    foreach (var file in convertedFiles.Take(10)) // 最多显示10个
                    {
                        result.AppendLine($"  {file}");
                    }
                    if (convertedFiles.Count > 10)
                    {
                        result.AppendLine($"  ... 还有 {convertedFiles.Count - 10} 个文件");
                    }
                    result.AppendLine();
                }

                if (failedFiles.Count > 0)
                {
                    result.AppendLine($"转换失败 {failedFiles.Count} 个文件：");
                    foreach (var file in failedFiles.Take(5)) // 最多显示5个失败的
                    {
                        result.AppendLine($"  {file}");
                    }
                    if (failedFiles.Count > 5)
                    {
                        result.AppendLine($"  ... 还有 {failedFiles.Count - 5} 个文件");
                    }
                }

                if (convertedFiles.Count == 0 && failedFiles.Count == 0)
                {
                    result.AppendLine("所有SVG文件名都已经是Unicode编码格式。");
                }

                MessageBox.Show(result.ToString(), "文件名转换结果", MessageBoxButton.OK, 
                    convertedFiles.Count > 0 ? MessageBoxImage.Information : MessageBoxImage.Warning);

                // 重新加载文件列表
                if (convertedFiles.Count > 0)
                {
                    LoadSvgFiles(txtSvgFolder.Text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"转换文件名时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private bool IsValidUnicodeFileName(string fileName)
        {
            // 检查文件名是否为有效的十六进制Unicode编码
            // 要求至少4位数字，避免将单个字母（如a、e）误认为是Unicode编码
            if (string.IsNullOrEmpty(fileName) || fileName.Length < 4)
                return false;
                
            return int.TryParse(fileName, NumberStyles.HexNumber, null, out int unicode) && unicode > 0;
        }

        private string ConvertTextToUnicodeFileName(string text)
        {
            if (string.IsNullOrEmpty(text))
                return null;

            try
            {
                // 如果文本只有一个字符，直接转换
                if (text.Length == 1)
                {
                    return ((int)text[0]).ToString("X4");
                }

                // 如果文本是多个字符，取第一个字符
                if (text.Length > 1)
                {
                    return ((int)text[0]).ToString("X4");
                }
            }
            catch
            {
                // 转换失败
            }

            return null;
        }
        
        private void TestSvgPathExtraction()
        {
            var logFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "svg_test_log.txt");
            var log = new List<string>();
            
            log.Add("=== SVG路径提取测试 ===");
            System.Diagnostics.Debug.WriteLine("=== SVG路径提取测试 ===");
            
            // 测试当前界面选择的文件夹
            var svgFolder = txtSvgFolder.Text;
            if (string.IsNullOrEmpty(svgFolder))
            {
                svgFolder = @"E:\字体辅助生成器\示例SVG";
            }
            
            var folderMsg = $"测试文件夹: {svgFolder}";
            log.Add(folderMsg);
            System.Diagnostics.Debug.WriteLine(folderMsg);
            
            if (!Directory.Exists(svgFolder))
            {
                var msg = $"SVG文件夹不存在: {svgFolder}";
                log.Add(msg);
                System.Diagnostics.Debug.WriteLine(msg);
                File.WriteAllLines(logFile, log);
                return;
            }
            
            var svgFiles = Directory.GetFiles(svgFolder, "*.svg");
            var filesMsg = $"找到 {svgFiles.Length} 个SVG文件\n";
            log.Add(filesMsg);
            System.Diagnostics.Debug.WriteLine(filesMsg);
            
            foreach (var svgFile in svgFiles)
            {
                var fileName = Path.GetFileName(svgFile);
                var fileMsg = $"处理文件: {fileName}";
                log.Add(fileMsg);
                System.Diagnostics.Debug.WriteLine(fileMsg);
                
                try
                {
                    var svgContent = File.ReadAllText(svgFile);
                    var lengthMsg = $"SVG内容长度: {svgContent.Length}";
                    log.Add(lengthMsg);
                    System.Diagnostics.Debug.WriteLine(lengthMsg);
                    
                    var contentMsg = $"SVG内容前100字符: {svgContent.Substring(0, Math.Min(100, svgContent.Length))}";
                    log.Add(contentMsg);
                    System.Diagnostics.Debug.WriteLine(contentMsg);
                    
                    // 使用反射调用私有方法ExtractSvgPath
                    var method = typeof(FontelloCliService).GetMethod("ExtractSvgPath", 
                        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    
                    if (method != null)
                    {
                        var result = method.Invoke(_fontelloCliService, new object[] { svgContent }) as string;
                        var resultMsg = $"提取的路径: {result}";
                        log.Add(resultMsg);
                        System.Diagnostics.Debug.WriteLine(resultMsg);
                        
                        if (string.IsNullOrEmpty(result) || result == "M100 100h800v800h-800z")
                        {
                            var warnMsg = "⚠️ 警告: 使用了默认路径，可能提取失败";
                            log.Add(warnMsg);
                            System.Diagnostics.Debug.WriteLine(warnMsg);
                        }
                        else
                        {
                            var successMsg = "✅ 成功提取SVG路径";
                            log.Add(successMsg);
                            System.Diagnostics.Debug.WriteLine(successMsg);
                        }
                    }
                    else
                    {
                        var errorMsg = "❌ 无法找到ExtractSvgPath方法";
                        log.Add(errorMsg);
                        System.Diagnostics.Debug.WriteLine(errorMsg);
                    }
                }
                catch (Exception ex)
                {
                    var exMsg = $"❌ 处理文件时出错: {ex.Message}";
                    log.Add(exMsg);
                    System.Diagnostics.Debug.WriteLine(exMsg);
                }
                
                var separator = new string('-', 60);
                log.Add(separator);
                System.Diagnostics.Debug.WriteLine(separator);
            }
            
            var completeMsg = "\n测试完成!";
            log.Add(completeMsg);
            System.Diagnostics.Debug.WriteLine(completeMsg);
            
            // 测试实际的转换过程
            TestActualConversionProcess(log, svgFiles);
            
            // 测试fontello-cli转换
            TestFontelloCliConversion(log, svgFolder);
            
            // 将所有日志写入文件
            File.WriteAllLines(logFile, log);
            
            var logMsg = $"测试日志已保存到: {logFile}";
            System.Diagnostics.Debug.WriteLine(logMsg);
        }
        
        private void TestActualConversionProcess(List<string> log, string[] svgFiles)
        {
            log.Add("\n=== 测试实际转换过程 ===");
            System.Diagnostics.Debug.WriteLine("\n=== 测试实际转换过程 ===");
            
            var glyphs = new List<object>();
            int currentUnicode = 0xE000; // 从私有使用区域开始
            
            foreach (var svgFile in svgFiles)
            {
                var fileName = Path.GetFileNameWithoutExtension(svgFile);
                int unicode;
                
                // 尝试解析Unicode编码（模拟FontelloCliService的逻辑）
                if (int.TryParse(fileName, System.Globalization.NumberStyles.HexNumber, null, out unicode))
                {
                    var hexMsg = $"文件 {fileName} 使用文件名作为Unicode: U+{unicode:X4} (字符: {(char)unicode})";
                    log.Add(hexMsg);
                    System.Diagnostics.Debug.WriteLine(hexMsg);
                }
                else
                {
                    unicode = currentUnicode++;
                    var assignMsg = $"文件 {fileName} 分配Unicode编码: U+{unicode:X4} (字符: {(char)unicode})";
                    log.Add(assignMsg);
                    System.Diagnostics.Debug.WriteLine(assignMsg);
                }
                
                // 创建字形对象（模拟实际转换过程）
                var glyph = new
                {
                    fileName = fileName,
                    unicode = unicode,
                    character = (char)unicode,
                    css = $"icon-{fileName.ToLower().Replace(" ", "-")}"
                };
                
                glyphs.Add(glyph);
            }
            
            var summaryMsg = $"\n总结: 处理了 {svgFiles.Length} 个文件，生成了 {glyphs.Count} 个字符";
            log.Add(summaryMsg);
            System.Diagnostics.Debug.WriteLine(summaryMsg);
            
            // 显示所有生成的字符
            foreach (var glyph in glyphs.Take(10)) // 只显示前10个
            {
                var glyphInfo = glyph.GetType().GetProperties()
                    .ToDictionary(p => p.Name, p => p.GetValue(glyph));
                var glyphMsg = $"字符: '{glyphInfo["character"]}' (U+{((int)glyphInfo["unicode"]):X4}) <- {glyphInfo["fileName"]}";
                log.Add(glyphMsg);
                System.Diagnostics.Debug.WriteLine(glyphMsg);
            }
            
            if (glyphs.Count > 10)
            {
                var moreMsg = $"... 还有 {glyphs.Count - 10} 个字符";
                log.Add(moreMsg);
                System.Diagnostics.Debug.WriteLine(moreMsg);
            }
        }
        
        private async void TestFontelloCliConversion(List<string> log, string svgFolder)
        {
            log.Add("");
            log.Add("=== 测试Fontello CLI转换 ===");
            
            try
            {
                var svgFiles = Directory.GetFiles(svgFolder, "*.svg");
                if (svgFiles.Length == 0)
                {
                    log.Add("没有找到SVG文件");
                    return;
                }
                
                var outputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test_output");
                Directory.CreateDirectory(outputFolder);
                
                log.Add($"开始转换 {svgFiles.Length} 个SVG文件");
                log.Add($"输出文件夹: {outputFolder}");
                
                // 获取字体名称（从用户界面或使用默认值）
                var testFontName = string.IsNullOrWhiteSpace(txtFontFamily.Text) ? "CustomFont" : txtFontFamily.Text;
                
                var success = await _fontelloCliService.ConvertSvgToFontAsync(
                     svgFiles.ToList(),
                     outputFolder,
                     testFontName, // fileName
                     _engineConfig.FontelloCli,
                     CancellationToken.None,
                     _performanceSettings,
                     testFontName, // fontName
                     testFontName, // fontFamily
                     "Unknown", // fontAuthor
                     "1.0" // fontVersion
                 );
                
                log.Add($"转换结果: {(success ? "成功" : "失败")}");
                
                if (Directory.Exists(outputFolder))
                {
                    var outputFiles = Directory.GetFiles(outputFolder, "*.*");
                    log.Add($"生成的文件数量: {outputFiles.Length}");
                    foreach (var file in outputFiles)
                    {
                        log.Add($"  - {Path.GetFileName(file)}");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Add($"测试Fontello CLI转换时发生错误: {ex.Message}");
            }
        }
    }
}